const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 路由
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// WebSocket连接处理
io.on('connection', (socket) => {
  console.log('用户连接:', socket.id);
  
  // 向客户端发送欢迎消息
  socket.emit('welcome', {
    message: '欢迎连接到WebSocket服务器！',
    timestamp: new Date().toLocaleString()
  });
  
  // 监听客户端消息
  socket.on('client_message', (data) => {
    console.log('收到客户端消息:', data);
    
    // 向所有客户端广播消息
    io.emit('server_broadcast', {
      user: socket.id,
      message: data.message,
      timestamp: new Date().toLocaleString()
    });
  });
  
  // 监听私聊消息
  socket.on('private_message', (data) => { //这里也是在监听emit的私密消息的信息
    console.log('私聊消息:', data);
    
    // 向指定客户端发送私聊消息
    socket.to(data.targetId).emit('private_message_received', {
      from: socket.id,
      message: data.message,
      timestamp: new Date().toLocaleString()
    });
  });
  
  // 处理断开连接
  socket.on('disconnect', () => {
    console.log('用户断开连接:', socket.id);
    
    // 通知其他用户有人离开
    socket.broadcast.emit('user_left', {
      userId: socket.id,
      timestamp: new Date().toLocaleString()
    });
  });
  
  // 心跳检测
  socket.on('ping', () => {
    socket.emit('pong', {
      timestamp: new Date().toLocaleString()
    });
  });
});

const PORT = process.env.PORT || 3001;
const HOST = '192.168.137.1'
server.listen(PORT,HOST, () => {
  console.log(`服务器运行在 http://${HOST}:${PORT}`);
});